package com.ronan.imweb.config;

import com.ronan.common.response.Result;
import com.ronan.common.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * FileName    : com.ronan.common.exception
 * Description :
 *
 * @author : ronan
 * @version : 1.0
 * Create Date : 2021/2/25 16:44
 **/
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * Validated 验证
     *
     * @param ex 异常
     * @return {@link Result}
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
        String errorMsg = fieldError.getDefaultMessage();
        log.error("MethodArgumentNotValidException getField:{}, msg:{}", fieldError.getField(), errorMsg);
        return Result.failedParam(errorMsg);
    }

    /**
     * 参数类型异常
     *
     * @param ex 参数
     * @return {@link Result}
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public Result handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
        log.error("参数类型异常 ex:{}", ex);
        return Result.failed(ResultCode.FAIL_PARAM_TYPE_INVALID.getCode(), ResultCode.FAIL_PARAM_TYPE_INVALID.getMsg());
    }

}
